import { _decorator, Node, Prefab, sys } from 'cc'
import { GAME_STATUS_ENUM, idioms } from './Enums'
import { generateMixedFragments, FragmentItem } from '../Utils/index'
const { ccclass, property } = _decorator
const STORAGE_KEY = 'STORAGE_KEY'
@ccclass('DataManager')
export class DataManager {
  private static _inst: DataManager
  static get inst(): DataManager {
    if (this._inst == null) {
      this._inst = new DataManager()
    }
    return this._inst
  }
  private _level: number = 1 // 当前关卡
  get level(): number {
    return this._level
  }
  set level(value: number) {
    this._level = value
  }
  // 所有成语
  idioms: string[] = idioms.slice(0, 30)
  // 随机打乱成语
  // splitShuffleIdioms: FragmentItem[] = []
  splitShuffleIdioms: FragmentItem[] = [
    // { word: '茅庐', mergeWord: ['三顾'] },
    // { word: '三', mergeWord: ['人成', '虎'] },
    // { word: '三顾', mergeWord: ['茅庐'] },
    // { word: '三', mergeWord: ['顾茅', '庐'] },
    // { word: '举', mergeWord: ['一反', '三'] },
    // { word: '顾茅', mergeWord: ['三', '庐'] },
    // { word: '一反', mergeWord: ['举', '三'] },
    // { word: '三', mergeWord: ['举', '一反'] },
    // { word: '虎', mergeWord: ['三', '人成'] },
    // { word: '人成', mergeWord: ['三', '虎'] },
    // { word: '庐', mergeWord: ['三', '顾茅'] },
    generateMixedFragments(idioms.slice(0, 10), 2),
    generateMixedFragments(idioms.slice(10, 30), 3),
  ].flat()
  // 当前字段下标
  currentIndex: number = 0
  // 已完成组合的成语
  completedIdioms: string[] = []
  // 游戏状态
  gameStatus: GAME_STATUS_ENUM = GAME_STATUS_ENUM.INIT
  // 当前关卡数据
  currentLevel = null
  // 在启动时绑定
  blockPrefab: Prefab = null!
  // 卷轴的节点数组
  idiomNodes: Node[] = []
  // 新生成卷轴成语的起始下标
  index = 0
  // 碰撞器处理
  public static collisionHandled = false

  currentWord() {
    const result = this.splitShuffleIdioms[this.currentIndex]
    this.currentIndex++
    return result
  }
  // 初始化数据
  reStart() {
    this.currentLevel = null
    this.currentIndex = 0
    this.index = Math.floor(Math.random() * idioms.length) - 30
    this.idioms = idioms.slice(this.index, this.index + 30)
    this.splitShuffleIdioms = [
      generateMixedFragments(this.idioms.slice(0, 10), 2),
      generateMixedFragments(this.idioms.slice(10), 3),
    ].flat()
    this.completedIdioms = []
    this.gameStatus = GAME_STATUS_ENUM.RUNNING
  }
  // 保存数据，下一关或重新开始时保存
  save() {
    sys.localStorage.setItem(
      STORAGE_KEY,
      JSON.stringify({
        currentLevel: 1,
      }),
    )
  }
  // 读取数据
  reStore() {
    const _data = sys.localStorage.getItem(STORAGE_KEY)
    const data = JSON.parse(_data)
    if (data) {
      this.currentLevel = data.currentLevel || null
    }
  }
}
